package tgc.edu.exam.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.edu.exam.custom.AjaxResult;
import tgc.edu.exam.entity.Permission;
import tgc.edu.exam.entity.SysRole;
import tgc.edu.exam.entity.TreeTableModel;
import tgc.edu.exam.form.MenuForm;
import tgc.edu.exam.form.RoleForm;
import tgc.edu.exam.service.PermissionService;
import tgc.edu.exam.service.SysRoleService;

@Controller
@RequestMapping("/role")
public class RoleController {
	@Autowired
	private SysRoleService roleService;
	@Autowired
	private PermissionService permissionService;

	@RequestMapping("/manage")
	public String manage() {
		return "role/manage";
	}
	@RequestMapping("/treeRoleList")
	@ResponseBody
	public Object treeRoleList() {
		Sort sort=Sort.by("idx1");
		List<SysRole> list = roleService.findAll(sort);
		return new TreeTableModel(list);
	}
	@RequestMapping("/edit")
	public String edit (RoleForm form,ModelMap map) throws InstantiationException, IllegalAccessException {
		SysRole model = new SysRole();
		Integer id = form.getId();
		Integer parentId = form.getParentId();
		if(id!=null) {
			model= roleService.findById(form.getId());
			parentId = model.getParentId();
		}
		if(parentId!=null) {
			SysRole parent = roleService.findById(parentId);
			model.setParent(parent);
		}
		map.put("model", model);
		if(parentId!=null) {
			List<Permission> permissions = permissionService.findAll(Sort.by("idx1"));
			map.put("roles", permissions);
		}
		return "role/edit";
	}
	@RequestMapping(value="/save")
	@ResponseBody
	public Object save(RoleForm form) {
		SysRole role = new SysRole();
		Integer id = form.getId();
		if(id!=null) {
			role = roleService.findById(id);
		}
		Integer parentId = form.getParentId();
		if(parentId==null) {
			role.setParent(null);
		}else {
			role.setParent(roleService.findById(parentId));
		}
		String pCode = form.getPermissionCode();
		if(StringUtils.hasText(pCode)) {
			Permission permission = permissionService.findByCode(pCode);
			role.setName(permission.getName());
			role.setCode(permission.getCode());
		}else {
			role.setName(form.getName());
			role.setCode(form.getCode());
		}
		role.setIdx1(form.getIdx1());
		roleService.save(role);
		return new AjaxResult("数据保存成功！");
	}
	@RequestMapping(value="/delete")
	@ResponseBody
	public Object delete(RoleForm form) {
		try {
			roleService.deleteById(form.getId());
			return new AjaxResult("数据删除成功");
		} catch (Exception e) {
			return new AjaxResult(false,"数据删除失败");
		}
	}
	
}
